package com.config.interceptor;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.zhima.dto.UserDTOExtension;
import com.zhima.util.UserHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zhima.constant.SystemConstant.AUTHORIZATION_HEADER;

public class ParseTokenInterceptor implements HandlerInterceptor {
    private final TokenStore tokenStore;
    private final boolean letGo;

    public ParseTokenInterceptor(TokenStore tokenStore, boolean letGo) {
        this.tokenStore = tokenStore;
        this.letGo = letGo;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tokenStr = request.getHeader(AUTHORIZATION_HEADER);
        if (tokenStr == null || CharSequenceUtil.isEmpty(tokenStr)) {
            return letGo;
        }
        // Bearer token
        String token = tokenStr.split(" ")[1];
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        UserDTOExtension userDTOExtension = JSONUtil.toBean(
                // 拿到当时认证的时候保存的UserDTOExtension对象转为的JSON字符串
                (String) accessToken.getAdditionalInformation().get("user_name"),
                UserDTOExtension.class);
        UserHolder.saveUser(userDTOExtension);
        return true;
    }
}
